import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Dimensions,
    FlatList,
    ImageBackground,
    PixelRatio,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    View
} from 'react-native';
import Header from "../components/Header";
import {MyStatusBar, STATUSBAR_HEIGHT} from "../components/MyStatusBar";
import ReaderControl from "../components/ReaderControl";
import MyLoading from "../components/MyLoading";
import Toast from "../components/Toast";
import tool from '../utils/tool';

import {options} from '../Global';
import LoadingUtil from "../utils/LoadingUtil";
import ctx from '../apis/index'
import Icon from "react-native-vector-icons/Ionicons";
import {setSpText2} from "../utils/ScreenUtil";
import NavigationEvents from "react-navigation/src/views/NavigationEvents";

const linePaddingLeft = 15;//每行左边距
const linePaddingRight = 15;//每行右边距
const titleHeight = 20;//顶部显示标题的高度
const pageNumberHeight = 20;//底部显示页码的高度
const fontSize = options.readerSettings.fontSize;//字体大小
const lineHeight = options.readerSettings.lineHeight;//每行的行高

const styles = StyleSheet.create({
    flex1: {
        flex: 1,
    },
    title: {
        height: titleHeight,
        lineHeight: titleHeight,
        fontSize: 12,
        paddingLeft: 5,
        marginBottom: 5,
        textAlign: 'left',
        color: '#666',
    },
    bottom: {
        flexDirection: 'row',
        paddingLeft: 5,
        paddingRight: 5,
        marginTop: 5,
    },
    bottomLeft: {
        flex: 1,
        height: pageNumberHeight,
        lineHeight: pageNumberHeight,
        fontSize: 12,
        textAlign: 'left',
        color: '#666',
    },
    bottomRight: {
        height: pageNumberHeight,
        lineHeight: pageNumberHeight,
        fontSize: 12,
        textAlign: 'right',
        color: '#666',
    },
    page: {
        height: pageNumberHeight,
        lineHeight: pageNumberHeight,
        fontSize: 12,
        paddingRight: 5,
        marginTop: 5,
        textAlign: 'right',
        color: '#666',
    },
    text: {
        fontSize: fontSize,
        lineHeight: lineHeight,
        // fontFamily: 'SourceHanSerifCN-Regular',
        fontFamily: Platform.OS === 'ios' ? 'FZLANTY_K--GBK1-0' : 'FZLanTYK',
    },
    row: {
        width: Dimensions.get('window').width,
        paddingLeft: linePaddingLeft,
        paddingRight: linePaddingRight,
    },
});

class ReaderScreen extends Component {
    constructor(props) {
        super(props);

        let {
            book,
            chapter,
            chapters,
            index
        } = this.props.navigation.state.params;
        this.state = {
            index: index,//当前章节位置，从0开始(正序)
            book: book,//小说信息object
            chapters: chapters,//所有章节(正序)array
            chapter: chapter,//当前章节object
            content: null,//当前内容object
            pagingData: [],//分页数据
            gotoEnd: false,//是否跳到内容末尾
            currentPage: 0,//第几页
            totalPage: 0,//共几页


            fontSize: fontSize,
            lineHeight: lineHeight,
        };

        this.visibleControl = false;
        this.scrollingOnHorizontal = false;//水平显示才有用，为了避免在scrollTo()自动调用handleScroll()
    }

    componentDidMount(): void {
        this.header.hide();
        this.control.hide();
        this.load(this.state.index);
    }

    render() {
        return (
            <ImageBackground
                source={require('../../assets/reader_bg.jpg')}
                style={styles.flex1}
            >
                <MyStatusBar backgroundColor="#f4511e"/>

                {/*返回刷新方法2*/}
                <NavigationEvents
                    // 当页面获得焦点的时候，调用刷新的函数（也就是从B页面返回的时候，会触发这个监听函数）
                    onWillFocus={e=>{
                        //返回当前页面时调用
                        if (this.state.fontSize === options.readerSettings.fontSize) {
                            //字体大小无改动，不需要刷新
                        } else {
                            this.callback();
                        }
                    }}
                    onWillBlur={(e) => {
                        //离开当前页面时调用
                    }}
                />

                <Header
                    ref={ref => this.header = ref}
                    headerLeftOnPress={() => this.props.navigation.goBack()}
                    headerRight={<Icon name={'ios-options'} size={24} color={'#f0f0f0'}/>}
                    headerRightOnPress={() => {
                        this.props.navigation.navigate('Options');

                        // 返回刷新方法1
                        // const {navigate} = this.props.navigation;
                        // navigate('Options', {
                        //     callback: (f, l) => {
                        //         //在此调接口或者改变state会让页面改变
                        //     }
                        // });
                    }}
                    headerStyle={{
                        position: 'absolute',
                        top: STATUSBAR_HEIGHT,
                    }}
                    headerTitle={this.state.chapter.title}
                />

                {this.renderChapterContent()}

                <ReaderControl
                    ref={control => this.control = control}
                    onCatalogPress={() => {
                        this.props.navigation.goBack()
                    }}
                    onPrevPress={() => {
                        this.prev(false);
                    }}
                    onNextPress={() => {
                        this.next();
                    }}
                />

                <MyLoading
                    ref={(ref) => {
                        global.mLoadingComponentRef = ref;
                    }}
                />
            </ImageBackground>
        );
    }

    callback = () => {
        let pagingData = tool.handleContent(this.state.content.body, options.readerSettings.fontSize, options.readerSettings.lineHeight);

        // 在前后面再拼接一页空白页 for android
        // let n = [[""]];
        let n = [], m = [];
        for (let i = 0; i < this.lines; i++) {
            m.push("");
        }
        n.push(m);
        n = n.concat(pagingData.concat(n));

        this.setState({
            // pagingData: pagingData,
            pagingData: n,
            currentPage: 1,
            totalPage: pagingData.length,
            fontSize: options.readerSettings.fontSize,
            lineHeight: options.readerSettings.lineHeight
        });

        if (this.scrollView) {
            this.scrollingOnHorizontal = false;
            setTimeout(() => {
                this.scrollView.scrollTo({
                    x: options.window.width * (this.state.gotoEnd ? pagingData.length : 1),
                    y: 0,
                    animated: false
                }, 1);
            });
            setTimeout(() => {
                this.scrollingOnHorizontal = true;
            }, 300);
        }
    };

    renderChapterContent = () => {
        if (this.state.pagingData.length === 0) {
            return;
        }
        let i = 0;
        return (
            <View style={styles.flex1} /*onLayout={(event) => console.log('layout', event.nativeEvent.layout)}*/>
                {this.renderTitle()}

                <ScrollView
                    style={styles.flex1}
                    scrollEventThrottle={800}
                    horizontal={true}
                    onScroll={(e) => this.onScroll(e)}
                    onScrollEndDrag={(e) => this.onScrollEndDrag(e)}
                    showsHorizontalScrollIndicator={false}
                    showsVerticalScrollIndicator={false}
                    pagingEnabled={true}
                    ref={scrollView => this.scrollView = scrollView}
                >
                    <FlatList
                        ref={(t) => {
                            this.list = t
                        }}
                        data={this.state.pagingData}
                        keyExtractor={item => 'line-' + i++}
                        horizontal={true}
                        renderItem={this.renderLine.bind(this)}
                    />
                </ScrollView>

                {this.renderPageNumber()}
            </View>
        );
    };

    renderPageNumber = () => {
        let p = this.state.currentPage;
        if (p < 1) {
            p = 1;
        }
        if (p >= (this.state.pagingData.length - 2)) {
            p = this.state.pagingData.length - 2;
        }
        return (
            <View style={styles.bottom}>
                <Text style={styles.bottomLeft}>字数：{this.state.content.body.length}</Text>
                <Text style={styles.bottomRight}>{p} / {this.state.totalPage}</Text>
            </View>
        );
    };

    renderTitle = () => {
        return (
            <Text style={styles.title} numberOfLines={1}>{this.state.chapter.title}</Text>
        );
    };

    renderLine = (rowData) => {
        let text = rowData.item.map((each, index) => {
            return (
                <Text key={'line' + index} style={[styles.text, {fontSize: setSpText2(this.state.fontSize), lineHeight: setSpText2(this.state.lineHeight)}]}>{each}</Text>
            );
        });
        return (
            <View style={[styles.row]}
                  onStartShouldSetResponder={() => true}
                  onResponderRelease={(evt) => {
                      this.showControl(evt)
                  }}
            >
                {text}
            </View>
        );
    };

    showControl = (evt) => {
        let pageX = evt.nativeEvent.pageX;
        let pageY = evt.nativeEvent.pageY;
        if (pageX > options.window.width / 3 && pageX < options.window.width * 2 / 3
            && pageY > options.window.height / 3 && pageY < options.window.height * 2 / 3) {

            if (!this.visibleControl) {
                this.header.show();
                this.control.show();
            } else {
                this.header.hide();
                this.control.hide();
            }
            this.visibleControl = !this.visibleControl;

        } else if (pageX < options.window.width / 3) {
            // 跳到上一页
            this.scrollView.scrollTo({
                x: options.window.width * (this.state.currentPage - 1),
                y: 0,
                animated: true
            }, 100);
        } else if (pageX > options.window.width * 2 / 3) {
            // 跳到下一页
            this.scrollView.scrollTo({
                x: options.window.width * (this.state.currentPage + 1),
                y: 0,
                animated: true
            }, 100);
        }
    };

    prev = (gotoEnd = true) => {
        if (this.state.index === 0) {
            Toast.show('前面没有了(*^_^*)');
            return;
        }
        let newIndex = this.state.index - 1;
        this.load(newIndex, gotoEnd);
    };

    next = () => {
        if (this.state.index === this.state.chapters.length - 1) {
            Toast.show('后面没有了(*^_^*)');
            return;
        }
        let newIndex = this.state.index + 1;
        this.load(newIndex);
    };

    /**
     * 加载章节内容
     * @param index 新章节索引位置
     * @param gotoEnd 是否跳到末尾
     * @private
     */
    load = (index, gotoEnd = false) => {
        LoadingUtil.showLoading();
        let newChapter = this.state.chapters[index];
        ctx.content(newChapter.link, this.state.book.source)
            .then(content => {
                LoadingUtil.dismissLoading();
                let pagingData = tool.handleContent(content.body, options.readerSettings.fontSize, options.readerSettings.lineHeight);

                // 在前后面再拼接一页空白页 for android
                // let n = [[""]];
                let n = [], m = [];
                for (let i = 0; i < this.lines; i++) {
                    m.push("");
                }
                n.push(m);
                n = n.concat(pagingData.concat(n));

                this.setState({
                    // pagingData: pagingData,
                    pagingData: n,
                    currentPage: 1,
                    totalPage: pagingData.length,
                    index: index,
                    chapter: newChapter,
                    content: content,
                    gotoEnd,
                    fontSize: options.readerSettings.fontSize,
                    lineHeight: options.readerSettings.lineHeight
                });

                if (this.scrollView) {
                    this.scrollingOnHorizontal = false;
                    setTimeout(() => {
                        this.scrollView.scrollTo({
                            x: options.window.width * (gotoEnd ? pagingData.length : 1),
                            y: 0,
                            animated: false
                        }, 1);
                    });
                    setTimeout(() => {
                        this.scrollingOnHorizontal = true;
                    }, 300);
                }
            })
            .catch(err => {
                LoadingUtil.dismissLoading();
                alert(err);
            })
        ;
    };

    onScroll = (e) => {
        let x = e.nativeEvent.contentOffset.x;
        let currentPage = Math.floor((x + linePaddingLeft + linePaddingRight) / options.window.width);
        this.setState({currentPage});

        if (x <= 0 && this.scrollingOnHorizontal) {
            this.prev();
        } else if (x > (options.window.width * (this.state.pagingData.length - 1) - 11) && this.scrollingOnHorizontal) {
            this.next();
        }
    };

    onScrollEndDrag = (e) => {
        let x = e.nativeEvent.contentOffset.x;
    };
}

export default ReaderScreen;